<template>
  <q-scroll-area class="timeline full-height" :thumb-style="thumbStyle">
    <div class="flex justify-center padding-20" style="position: relative">
      <div class="flex items-center">
        <q-btn round color="primary" size="6px" icon="chevron_left" style="margin: 0 10px"
               @click="prevDate()" />
        <date-picker v-model="selDate" valueType="format" placeholder="选择日期"></date-picker>
        <q-btn round color="primary" size="6px" icon="chevron_right" style="margin: 0 10px"
               @click="nextDate()" />
        <q-btn color="primary" label="返回今天" @click="returnToday"
               :disable="selDate == $utils.formatDate(new Date())" />
      </div>
      <q-toggle v-model="showScale"
                label="启用缩放"
                left-label
                @input="scale"
                style="position: absolute; right: 20px; height: 30px"
      />
    </div>

    <!-- 班次 -->
    <div v-for="i in 4" :key="i" v-show="scheduling[i - 1]"
         class="flex margin-t-20 rounded-borders margin-l-20 margin-r-20 text-white overflow-hidden"
         style="border: 1px solid #d3d3d3;height: 260px">
      <div class="card-title text-center font-size-16 flex items-center"
           style="background-color: #5F77FD">
        {{ scheduling[i - 1] ? scheduling[i - 1].name : '' }}
      </div>
      <!-- 图表 -->
      <div class="chart" style="width: calc(100% - 48px); height: 100%; display: block;" />
    </div>
    <div class="flex margin-t-20 rounded-borders margin-l-20 margin-r-20 text-white overflow-hidden"
         style="border: 1px solid #d3d3d3;height: 260px" v-if="productList.length > 0">
      <div class="card-title text-center font-size-16 flex items-center"
           style="background-color: #44D8C6">循环统计
      </div>
      <div class="product-list flex overflow-hidden text-black" v-if="productList.length <= 3">
        <div class="product-item rounded-borders" v-for="(item,index) in productList" :key="index">
          <div class="text-ellipsis title text-center font-size-16">
            {{item.productName || '--'}}({{item.processName || '--'}})
            <q-tooltip>{{item.productName || '--'}}({{item.processName || '--'}})</q-tooltip>
          </div>
          <div class=" flex text-center" style="height: calc(100% - 57px)">
            <div style="flex:1;padding-top: 60px">
              <div class="margin-b-10">总循环</div>
              <div style="font-size: 24px">{{item.count}}次循环</div>
            </div>
            <div style="flex:1;padding-top: 60px">
              <div class="margin-b-10">平均循环时间</div>
              <div style="font-size: 24px">{{getDuration(item.averageDuration)}}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="product-list text-black" style="padding: 0" v-else>
        <swiper :options="swiperOption" style="height: inherit;padding: 0 20px">
          <swiper-slide v-for="(item,index) in productList" :key="index">
            <div class="product-item rounded-borders">
              <div class="text-ellipsis title text-center font-size-16">
                {{item.productName || '--'}}({{item.processName || '--'}})
                <q-tooltip>{{item.productName || '--'}}({{item.processName || '--'}})</q-tooltip>
              </div>
              <div class=" flex text-center" style="height: calc(100% - 57px)">
                <div style="flex:1;padding-top: 60px">
                  <div class="margin-b-10">总循环</div>
                  <div style="font-size: 24px">{{item.count}}次循环</div>
                </div>
                <div style="flex:1;padding-top: 60px">
                  <div class="margin-b-10">平均循环时间</div>
                  <div style="font-size: 24px">{{getDuration(item.averageDuration)}}</div>
                </div>
              </div>
            </div>
          </swiper-slide>
          <div class="swiper-button-prev" slot="button-prev">
            <q-btn round color="primary" size="13px" icon="chevron_left" style="margin: 0" />
          </div>
          <div class="swiper-button-next" slot="button-next">
            <q-btn round color="primary" size="13px" icon="chevron_right" style="margin: 0" />
          </div>
        </swiper>
      </div>
    </div>
    <div class="flex justify-between padding-20 margin-t-20 " style="padding-bottom: 10px">
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['normal-cycle'].id,name:CommonConfig.statData.machine['normal-cycle'].name}"
           @click="showNormalDetail">
        <q-icon class="iconfont icontubiao-123" style="font-size: 48px;color: #44d8c6" />
        <div class="font-size-16">正常循环明细</div>
        <div class="font-size-16 margin-t-10">(共{{normalList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['downtime-detail'].id,name:CommonConfig.statData.machine['downtime-detail'].name}"
           @click="showDowntimeDurationDetail">
        <q-icon class="iconfont icontubiao-121" style="font-size: 48px;color: #ff8559" />
        <div class="font-size-16">停机时间明细</div>
        <div class="font-size-16 margin-t-10">(共{{downtimeList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['warning-detail'].id,name:CommonConfig.statData.machine['warning-detail'].name}"
           @click="showWarningDetail">
        <q-icon class="iconfont icontubiao-78" style="font-size: 48px;color: #e43434" />
        <div class="font-size-16">报警明细</div>
        <div class="font-size-16 margin-t-10">(共{{warningList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['close-detail'].id,name:CommonConfig.statData.machine['close-detail'].name}"
           @click="showCloseDetail">
        <q-icon class="iconfont icontubiao-144" style="font-size: 48px;color: #666" />
        <div class="font-size-16">离线明细</div>
        <div class="font-size-16 margin-t-10">(共{{offlineList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center"
           v-stat="{id:CommonConfig.statData.machine['abnormal-list'].id,name:CommonConfig.statData.machine['abnormal-list'].name}"
           @click="showAbnormalDetail">
        <q-icon class="iconfont icontubiao-113" style="font-size: 48px;color: #f7b82d" />
        <div class="font-size-16">异常循环明细</div>
        <div class="font-size-16 margin-t-10">(共{{abnormalList}}次)</div>
      </div>
    </div>
    <!-- 正常循环明细 -->
    <normal-cycle
      :show="normal.show"
      :since="since"
      :before="before"
      :boxId="params.boxId"
      @close="normal.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 停机时长明细 -->
    <downtime-duration-detail
      :show="downtimeDuration.show"
      :since="since"
      :before="before"
      :boxId="params.boxId"
      @close="downtimeDuration.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 报警明细 -->
    <warning-detail
      :show="warning.show"
      :since="since"
      :before="before"
      :boxId="params.boxId"
      @close="warning.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 离线明细 -->
    <close-detail
      :show="closeDetail.show"
      :since="since"
      :before="before"
      :boxId="params.boxId"
      @close="closeDetail.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 异常明细 -->
    <abnormal-detail
      :show="abnormalDetail.show"
      :since="since"
      :before="before"
      :boxId="params.boxId"
      @close="abnormalDetail.show = false"
      @initData="initData()"
      @getDetailedCount="getDetailedCount()"
    />
  </q-scroll-area>
</template>

<script>
import normalCycle from './components/normal-cycle'
import downtimeDurationDetail from './components/downtime-duration-detail'
import warningDetail from './components/warning-detail'
import closeDetail from './components/close-detail'
import abnormalDetail from './components/abnormal-detail'
import { MachineStatsChart } from './machine-stats-chart'
import { date } from 'quasar'
import {
  getMachineTimelineData,
  getStartDateTime, getProductList, getDetailedCount
} from '../../boot/status/machine'
import echarts from 'echarts'

export default {
  name: 'timeline',
  props: {
    msg: {
      type: String,
      default: ''
    },
    details: {
      type: String,
      default: ''
    }
  },
  components: {
    normalCycle,
    downtimeDurationDetail,
    warningDetail,
    closeDetail,
    abnormalDetail
  },
  created () {
    this.params = JSON.parse(this.details)

    console.log(this.params, '时间线')
  },
  watch: {
    details (val) {
      this.params = JSON.parse(this.details)
      // console.log(this.params.boxId, 'change时间线')
      this.getStartDateTime()
    },
    selDate (val) {
      if (val) {
        this.getStartDateTime()
      }
      // this.renderCharts()
    }
  },
  mounted () {
    this.selDate = this.$utils.formatDate(new Date())
    this.nowDate = this.$utils.formatDate(new Date())
    this.initCharts()
    window.addEventListener('resize', () => {
      this.charts.forEach(o => o.resize().rerender())
    })

    this.getStartDateTime()
  },
  data () {
    return {
      params: {}, // 状态页卡片传参
      since: null, // 当天班制开始时间
      before: null, // 当天班制结束时间
      normalList: 0, // 正常循环数量
      downtimeList: 0, // 停机循环数量
      warningList: 0, // 报警循环数量
      abnormalList: 0, // 异常明细数量
      offlineList: 0, // 离线数量
      scheduling: [{}, {}, {}, {}],
      charts: [],
      selDate: '',
      showScale: false, // 是否可以缩放
      // 停机时长明细
      downtimeDuration: {
        show: false
      },
      // 正常明细
      normal: {
        show: false
      },
      // 报警明细
      warning: {
        selected: [],
        show: false
      },
      // 报警明细
      closeDetail: {
        selected: [],
        show: false
      },
      // 异常明细
      abnormalDetail: {
        selected: [],
        show: false
      },
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      productList: [],
      swiperOption: {
        slidesPerView: 3,
        spaceBetween: 20,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        }
      }
    }
  },
  methods: {
    scale () {
      this.charts.map(v => {
        v._changeZoom(!this.showScale).rerender()
      })
    },
    /**
     * 初始化图表
     */
    initCharts () {
      document.querySelectorAll('.chart').forEach(el => {
        this.charts.push(new MachineStatsChart(echarts.init(el)))
      })
    },
    initData () {
      this.renderCharts()
      this.getProductList()
      this.getDetailedCount()
    },
    // 获取当天班制开始结束时间
    getStartDateTime () {
      getStartDateTime(this.params.boxId, this.params.id, this.selDate).then(res => {
        if (res.data && res.data.since && res.data.before) {
          this.since = res.data.since
          this.before = res.data.before
          this.initData()
        } else {
          this.$q.dialog({
            title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-53" ></i> 当天无有效班制</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
        }
      })
    },
    // 获取产品循环统计
    getProductList () {
      getProductList(this.params.boxId, this.since, this.before).then(res => {
        res.data.forEach(o => {
          o.productName = o.productName.indexOf('-') === -1 ? o.productName : '无'
        })
        this.productList = res.data
      })
    },
    // 转换时长
    getDuration (second) {
      var days = Math.floor(second / 86400)
      var hours = Math.floor((second % 86400) / 3600)
      var minutes = Math.floor(((second % 86400) % 3600) / 60)
      var seconds = Math.floor(((second % 86400) % 3600) % 60)
      var duration = (days > 0 ? days + '天' : '') + (hours > 0 ? hours + '小时' : '') + (minutes > 0 ? minutes + '分' : '') + seconds + '秒'
      return duration
    },
    // 获取明细数量
    getDetailedCount () {
      getDetailedCount(this.params.boxId, this.since, this.before).then(res => {
        this.normalList = res.data.normalWorkpiece
        this.downtimeList = res.data.stop
        this.warningList = res.data.alarm
        this.offlineList = res.data.offline
        this.abnormalList = res.data.abnormalWorkpiece
      })
    },
    /**
     * 渲染数据到图表
     */
    async renderCharts () {
      this.charts.forEach(chart => chart.getInstance().showLoading())

      await this.getMachineStats()

      this.scheduling.forEach((aScheduling, i) => {
        this.charts[i]
          .setSchedulingTime(new Date(aScheduling.from), new Date(aScheduling.to))
          .setData({
            rests: aScheduling.rests,
            stats: aScheduling.events
          })
          .rerender()
      })

      this.charts.forEach(chart => chart.getInstance().hideLoading())
    },
    getMachineStats () {
      return getMachineTimelineData(this.params.boxId, this.params.id, this.selDate)
        .then(res => {
          this.scheduling = res.data.shifts
        })
    },
    // 下一天
    nextDate () {
      this.selDate = this.$utils.formatDate(date.addToDate(this.selDate, { days: 1 }))
      // this.getStartDateTime()
    },
    // 上一天
    prevDate () {
      this.selDate = this.$utils.formatDate(date.subtractFromDate(this.selDate, { days: 1 }))
      // this.getStartDateTime()
    },
    // 返回今日
    returnToday () {
      this.selDate = this.$utils.formatDate(new Date())
      // this.getStartDateTime()
    },
    showNormalDetail () {
      this.normal.show = true
    },
    showWarningDetail () {
      this.warning.show = true
    },
    showCloseDetail () {
      this.closeDetail.show = true
    },
    showDowntimeDurationDetail () {
      this.downtimeDuration.show = true
    },
    showAbnormalDetail () {
      this.abnormalDetail.show = true
    }
  }
}
</script>

<style scoped lang="stylus">
  .padding-20 {
    padding 0 20px
  }

  .detail-item {
    flex 1
    cursor pointer
    height 175px
    box-shadow 0px 1px 7px 0px rgba(0, 0, 0, 0.15)
  }

  .card-title {
    width 48px
    height inherit
    padding 0 16px
  }

  .product-list {
    height inherit
    width calc(100% - 48px)
    padding 0 20px
  }

  .product-item {
    box-shadow 0px 1px 7px 0px rgba(0, 0, 0, 0.15)
    height inherit
    flex 1
    margin-right 20px
    padding 0 10px

    .title {
      line-height 56px
      border-bottom $border
    }
  }

  .product-item:last-child {
    margin 0
  }

  .swiper-button-prev, .swiper-button-next {
    background-image none
    width 39px
    height 39px
  }
</style>
